get file extension python

59

how to search for a specific file extension with python -

import glob, os
os.chdir("/mydir")
for file in glob.glob("*.txt"):
    print(file)

split filename and extension python -

>>> import os
>>> filename, file_extension = os.path.splitext('/path/to/somefile.ext')
>>> filename
'/path/to/somefile'
>>> file_extension
'.ext'

python get file extension from path -

import os.path
extension = os.path.splitext(filename)[1]

get file extension python -

import pathlib

print(pathlib.Path('yourPath.example').suffix) # '.example'
#or 
import os
filename, file_extension = os.path.splitext('/path/to/somefile.ext')

Comments

Submit
0 Comments